<!--
* @description 弹出日期选择
* @author zywu
* @date 2021/03/16 20:49:19
!-->
<template>
  <div class="pop-datepicker">
    <pop-button
      :is-active="!!currentDate"
      :is-open="active"
      :text="textShow"
      :align="align"
      @click.native="handleClick"
    ></pop-button>
    <van-popup v-model="active" round position="bottom">
      <van-datetime-picker v-model="currentDate" :type="type" title="选择年月" @confirm="onConfirm" @cancel="onCancel" />
    </van-popup>
  </div>
</template>

<script>
import PopButton from '@/components/PopButton'
export default {
  props: {
    type: {
      type: String,
      default: 'year-month',
    },
    text: String,
    defaultDate: {
      type: Date,
      default: function () {
        return new Date()
      },
    },
    align: {
      type: String,
      default: 'center',
    },
  },
  data() {
    return {
      active: false,
      currentDate: new Date(),
      confirmDate: new Date(),
    }
  },

  components: { PopButton },

  computed: {
    textShow() {
      return this.$moment(this.confirmDate).format('yyyy年MM月')
    },
  },

  watch: {
    active(val) {
      this.currentDate = this.confirmDate
    },
    defaultDate(val) {
      if (val) {
        this.setValue(val)
      }
    },
  },

  created() {
    if (this.defaultDate) {
      this.setValue(this.defaultDate)
    }
  },

  mounted() {},

  methods: {
    setValue(val) {
      this.currentDate = val
      this.confirmDate = val
    },
    onConfirm(val) {
      this.confirmDate = val
      this.active = false
      this.$emit('change', val)
    },
    handleClick() {
      this.active = !this.active
    },
    onCancel() {
      this.active = false
    },
  },
}
</script>
<style lang='scss'>
@import '../styles/variables.scss';
.pop-datepicker {
  .van-picker__confirm {
    color: $color-theme;
  }
}
</style>